<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :class="{'mobile-el-dialog': showMobilePage}"
    class="large-common-dialog-size related-cost-dialog">
    <Title title="关联成本" font-size="16px" style="margin: 0 0 16px"/>
    <div class="dialog-scroll">
      <div class="header-form" style="padding-bottom: 12px;">
        <FilterInput ref="FilterToolRef" v-model="paramsObj" :filter-list="filterList" show-search-btn @handelClick="queryClick" @queryEmpty="queryEmpty" />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <el-table
            v-if="list.items.length > 0"
            ref="projectTableRef"
            :data="list.items"
            :row-class-name="(data) => tableRowClassName(data)"
            height="360"
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            row-key="id"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable">
            <el-table-column
              type="selection"
              align="center"
              width="50" />
            <el-table-column align="left" label="成本编号" width="180">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.costNum" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.costNum }}</div>
                  <router-link
                    :to="{name: 'costDetail', params: { id: scope.row.id }}"
                    class="project-num"
                  ><div class="ellipsis">{{ scope.row.costNum }}</div></router-link>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="成本项" width="100">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.costItemName" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.costItemName }}</div>
                  <div class="ellipsis">{{ scope.row.costItemName }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="right" label="含税成本(元)" min-width="130" prop="taxCost">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.taxCost" :price="scope.row.taxCost / 100" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="供应商" width="120">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.supplierName" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.supplierName }}</div>
                  <div class="ellipsis">{{ scope.row.supplierName }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="说明" width="160">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.costDescription" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.costDescription }}</div>
                  <div class="ellipsis">{{ scope.row.costDescription }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="成本状态" width="80">
              <template slot-scope="scope">
                {{ scope.row.settlementStatus | settlementStatusFilter }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="成本类型" width="80">
              <template slot-scope="scope">
                {{ scope.row.costType | costTypeFilter }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="所属部门" width="140">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.departmentName" />
              </template>
            </el-table-column>
            <el-table-column align="left" label="申请人" width="90">
              <template slot-scope="scope">
                {{ scope.row.proposer || '--' }}
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建时间" min-width="180" prop="createDate">
              <template slot-scope="scope">
                <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm') }}</div>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建人" width="90">
              <template slot-scope="scope">
                {{ scope.row.creator || '--' }}
              </template>
            </el-table-column>
          </el-table>
          <empty-placeholder v-else style="margin-bottom: 24px" />
        </div>
      </div>
    </div>
    <div v-if="showMobilePage">
      <el-pagination
        v-show="list.total > 0"
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        layout="total, prev, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <div :class="{'foot-container': !showMobilePage}">
      <div class="opeator">
        <el-button :loading="opeatorLoading" type="primary" class="batch-button" size="small" @click.native="toRelate">关联成本</el-button>
      </div>
      <template v-if="!showMobilePage">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </div>
  </el-dialog>
</template>
<script>
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { costType, settlementStatus } from '@/views/cost/model/selectData';
import { getCostList } from '@/api/costManage';
import { getDepartment } from '@/api/project';
import { costList } from '@/api/config';
import { relatedCost } from '@/api/order';
import { settlementStatusFilter, costTypeFilter } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormat } from '@/filters/date';
import ElMessage from '@/utils/message';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import tableSelections from '@/mixins/tableSelections';
import { mapState } from 'vuex';

export default {
  components: { Title, EmptyPlaceholder },
  filters: {
    moneyFilter,
    settlementStatusFilter,
    costTypeFilter,
    standardFormat },
  mixins: [tableSelections],
  props: {
    orderId: {
      type: String | Number,
      default: ''
    },
    costBelongType: { // 成本来源
      type: Number,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      paramsObj: {},
      departmentOption: [],
      costItem: [],
      opeatorLoading: false,
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      ids: '',
      tableHeight: null,
      listLoading: false,
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createDateStart',
        end: 'createDateEnd',
        type: 'time'
      }],
      tableRefName: 'projectTableRef', // 表格的ref名称
      idKey: 'id' // 唯一表示字段
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'costNum', name: '成本编号', type: 'input' },
        { keyword: 'supplierName', name: '供应商', type: 'input' },
        { keyword: 'costDescription', name: '说明', type: 'input' },
        // 下拉
        { keyword: 'settlementStatus', name: '成本状态', type: 'select', options: settlementStatus },
        { keyword: 'departmentId', name: '所属部门', type: 'select', isSearch: true, options: this.departmentOption }, // 可搜索下拉
        { keyword: 'costItemId', name: '成本项', type: 'select', options: this.costItem },
        { keyword: 'costType', name: '成本类型', type: 'select', options: costType },
        // 日期
        { keyword: 'createTime', name: '创建时间', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    }
  },
  watch: {
    dialogVisible: {
      handler(val) {
        if (val) {
          this.multipleSelectionAll = [];
          this.ids = '';
          this.fetchData(true);
        }
      },
      immediate: true
    }
  },
  mounted() {
    // const elDialog = document.querySelector('.related-cost-dialog .el-dialog');
    // const clientHeight = window.innerHeight;
    // elDialog.style.maxHeight = (clientHeight * 3) / 3.4 + 'px';
  },
  created() {
    this.getDepartmentData();
    this.getCostItemList();
    // this.fetchData(true);
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      params.costBelong = this.costBelongType;
      // 时间处理
      /* if (params.createTime && params.createTime.length === 2) {
        params.createDateStart = Math.round(params.createTime[0] / 1000);
        params.createDateEnd = Math.round(params.createTime[1] / 1000);
      }
      delete params.createTime; */
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.isNotRelateOrder = 0;
      this.listLoading = true;
      getCostList(params).then(({ data, code }) => {
        data.items.map(item => {
          if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }).catch(e => {
        console.error(e);
        this.listLoading = false;
      });
    },
    // 多选
    tableSelectionChange(e) {
      this.ids = e.map(i => i.id).join(',');
    },
    clearSelection() {
      if (this.$refs[this.tableRefName]) this.$refs[this.tableRefName].clearSelection();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    // 获取成本管理下包含的部门
    getDepartmentData() {
      const params = {
        type: 6
      };
      getDepartment(params).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      });
    },
    // 获取成本项列表
    getCostItemList() {
      costList().then(res => {
        if (res.data) {
          const costItem = res.data.items;
          costItem.forEach(item => {
            item.value = item.costId;
            item.label = item.costName;
          });
          this.costItem = costItem;
        }
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    toRelate() {
      if (!this.ids) {
        ElMessage.error('请选择成本');
        return;
      }
      relatedCost(this.orderId, { ids: this.ids }).then(res => {
        this.$message.success('关联成功');
        this.dialogVisible = false;
        this.$emit('updateCostList');
      }).catch(err => {
        console.error(err);
        this.dialogVisible = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.related-cost-dialog {
  & ::v-deep {
    .el-dialog {
      height: 560px;
    }
  }
  .dialog-scroll {
    @include scrollBar();
  }
  .foot-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 10px;
    .opeator {
      flex:1;
    }
  }
}
</style>
